import 'dart:io';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'progress_webview.dart';

class WebViewTestPage extends StatefulWidget {
  const WebViewTestPage({super.key});

  @override
  State<WebViewTestPage> createState() => _WebViewTestPageState();
}

class _WebViewTestPageState extends State<WebViewTestPage> {
  WebViewController? _controller;

  final String _initialUrl =
      "https://test1.baomi.org.cn/portal/sites/distH5/pages/index.html#/news/organInformation?id=2027119&docLibId=68718&doc_type=文章新闻&pubId=5878&siteId=95&token=242e28cab3ae4615b9fb0f2d1e54f50d";

  @override
  Widget build(BuildContext context) {
    return ProgressWebView(
      initialUrl: _initialUrl,
      injectFontFamily: true,
      injectTitleFontFamily: true,
      onWebViewCreated: (webViewController) {
        _controller = webViewController;
      },
      onPageStarted: (String url) {},
      onPageFinished: (String url) {},
      navigationDelegate: (NavigationRequest navigation) {
        return onNavigationDelegate(navigation);
      },
    );
  }

  bool navigationUrlIn = false; //导航中

  //前端通讯拦截
  Future<NavigationDecision> onNavigationDelegate(
      NavigationRequest navigation) async {
    String navigationUrl = navigation.url;

    if (navigationUrl.startsWith("http")) {
      if (navigationUrlIn) {
        print('导航中  NavigationDecision.navigate');
        return NavigationDecision.prevent;
      }
      navigationUrlIn = true;
      if (Platform.isIOS) {
        String? decodeUri;
        try {
          decodeUri = Uri.encodeFull(_initialUrl);
          if (decodeUri == navigationUrl) {
            print('路由拦截  NavigationDecision.navigate');
            navigationUrlIn = false;
            return NavigationDecision.navigate;
          }
        } catch (e, s) {
          debugPrintStack(stackTrace: s);
        }
      }
      await Future.delayed(Duration(milliseconds: 500));
      navigationUrlIn = false;
      print('路由拦截  NavigationDecision.prevent');
      return NavigationDecision.prevent;
    }
    return NavigationDecision.navigate;
  }
}
